package com.cos.hospital.ui.patient.adapter;

import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cos.hospital.R;
import com.cos.hospital.code.helper.KTextWatcher;
import com.cos.hospital.model.bean.SurplusCureBean;
import com.cos.hospital.tool.UTxt;

import java.util.List;

/**
 * 治疗项目次数适配器
 */
public class CureCountAdapter extends BaseQuickAdapter<SurplusCureBean.ItemsBean, BaseViewHolder> {

    public CureCountAdapter(@Nullable List<SurplusCureBean.ItemsBean> data) {
        super(R.layout.item_cure_count, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, SurplusCureBean.ItemsBean item) {
        helper.setText(R.id.tv_name, item.getFldItemName());

        EditText edt_count = helper.getView(R.id.edt_count);
        //第1步：为了避免TextWatcher在第2步被调用，提前将他移除。
        if (edt_count.getTag() instanceof TextWatcher) {
            edt_count.removeTextChangedListener((TextWatcher) edt_count.getTag());
        }
        //第2步：移除TextWatcher之后，设置EditText的Text。
        edt_count.setText(item.getFldNum() + "");
        TextWatcher textWatcher = new KTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                int count;
                if (UTxt.isEmpty(editable.toString())) {
                    item.setFldNum(0);
                    return;
                }
                count = Integer.parseInt(editable + "");
                int o = count;
                if (count > 100) {
                    count = 100;
                }
                if (count < 0) {
                    count = 0;
                }
                item.setFldNum(count);
                if (count == o) {
                    return;
                }
                edt_count.setText(count + "");
            }
        };
        edt_count.addTextChangedListener(textWatcher);
        edt_count.setTag(textWatcher);

        helper.addOnClickListener(R.id.iv_reduce);
        helper.addOnClickListener(R.id.iv_add);
    }
}